package com.zz.bid.util;

import com.zz.bid.exception.DirectoryAlreadyExistException;
import com.zz.bid.exception.base.BidException;
import com.zz.bid.exception.base.DirectoryCreateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Slf4j
public class FileUtil {

    private static final String BID_FILE_PATH = "/root/bid/bids/";
    private static final String SETTLE_FILE_PATH = "/root/bid/settles/";

    public static void mkdir(String path) throws BidException {
        File dir = new File(path);
        log.debug("mkdir " + path);
        if (dir.exists()) {
            throw new DirectoryAlreadyExistException();
        }
        if (!dir.mkdirs()) {
            throw new DirectoryCreateException();
        }
    }

    public static void storeFile(MultipartFile file, String path) throws BidException {
        try {
            //暂时不做字符处理
            Assert.notNull(file.getOriginalFilename(), "origin filename is null");
            String[] strs = file.getOriginalFilename().split("/");
            String filename = strs[strs.length - 1];
            Path targetLocation = Paths.get(path + File.separator + filename).toAbsolutePath().normalize();
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BidException("文件上传失败: " + file.getOriginalFilename());
        }
    }


    public static Resource loadFileAsResource(String filePath) throws BidException {
        try {
            Resource resource = new FileSystemResource(new File(filePath));
            if (resource.exists()) {
                return resource;
            } else {
                throw new BidException("未找到文件: " + filePath);
            }
        } catch (Exception ex) {
            throw new BidException("未找到文件: " + filePath);
        }
    }

    public static String getBidPath(Integer bidId, String flowName) {
        return BID_FILE_PATH + bidId + File.separator + flowName;
    }

    public static String getSettlePath(Integer settleId, String flowName) {
        return SETTLE_FILE_PATH + settleId + File.separator + flowName;
    }
}
